'''
Created on 29/09/2012

@author: Christian
'''


import MySQLdb

class MySQLDB(object):


    def __init__(self):
        self._host = "localhost"
        self._user = "root"
        self._passwd = "polimero"
        self._schema = "VCS2DB"
        
    def connect(self):
        connection = MySQLdb.connect (host=self._host,
                                      user=self._user,
                                      passwd=self._passwd,
                                      db=self._schema)
        self._db = connection.cursor()
        print "DB Connection established..."

    def registerProject(self, projectname, pathurl, vcstype):
        query = "INSERT INTO VCS2DB.REPOSITORY (NAME, URL, TYPE) VALUES (%s,%s,%s)"
        self._db.execute(query, (projectname, pathurl, vcstype))
        print "Project '%s' registered with id %s" % (projectname, self._db.lastrowid)
        return self._db.lastrowid
    
    def getLastInsertedId(self):
        query = "SELECT id FROM VCS2DB.CHANGE ORDER BY ID DESC LIMIT 1"
        self._db.execute(query)
        lastinsertedid = self._db.fetchone() 
        if not lastinsertedid:
            lastid = 0
        else:
            lastid = lastinsertedid[0]
        return lastid + 1
    
    def saveChangesAndFiles(self, changes, files):
        print "Inserting changes..."
        querychanges = """INSERT INTO VCS2DB.CHANGE (ID, REV, NODE, USER_NAME, USER_EMAIL, DATE_UNIX, DATE, PARENT_A, PARENT_B, MERGE, DESCRIPTION, REPOSITORY_ID ) 
                       VALUES (%s, %s, %s, %s, %s, %s, FROM_UNIXTIME(%s), %s, %s, %s, %s, %s)"""
        self._db.executemany(querychanges, changes)
        
        print "Inserting change files..."
        queryfiles = """INSERT INTO VCS2DB.CHANGE_FILE (FILE, EXTENSION, MODIFICATION, CHANGE_ID)
                     VALUES (%s, %s, %s, %s)""" 
        self._db.executemany(queryfiles, files)
        
    def getProjectIdByName(self, projectname):
        query = """SELECT ID FROM VCS2DB.REPOSITORY WHERE NAME = '%s'""" % projectname
        self._db.execute(query)
        return self._db.fetchone()[0]

        
